/* eslint-disable no-bitwise */
import react_native_blob_util from 'react-native-blob-util';

import { downloadFile } from '../downloadFile';
const { fs: RNFS } = react_native_blob_util;

class VideoCacheManager {
  private cacheDir: string;

  constructor() {
    // iOS 和 Android 使用不同的缓存目录
    this.cacheDir = `${RNFS.dirs.CacheDir}/video-cache`;
    this.initCacheDir();
  }

  private async initCacheDir() {
    const exists = await react_native_blob_util.fs.exists(this.cacheDir);
    if (!exists) {
      await RNFS.mkdir(this.cacheDir);
    }
  }

  // 简单的哈希函数
  private generateHash(str: string): string {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i);
      hash = (hash << 5) - hash + char;
      hash = hash & hash; // Convert to 32-bit integer
    }
    return Math.abs(hash).toString(16);
  }
  // 获取缓存文件路径
  private getCacheFilePath(url: string): string {
    const fileName = this.generateHash(url);
    return `${this.cacheDir}/${fileName}.mp4`;
  }

  // 检查视频是否已缓存
  private async isVideoCached(url: string): Promise<boolean> {
    const filePath = this.getCacheFilePath(url);
    return await RNFS.exists(filePath);
  }

  // 下载视频到缓存
  private async downloadVideo(url: string, filePath: string): Promise<string> {
    console.log('downloadVideo===', { url, filePath });
    try {
      const response = await downloadFile.downloadVideo(url, {
        path: filePath,
        IOSBackgroundTask: true,
      });

      if (response?.info().status === 200) {
        return response.path();
      }
      throw new Error('Download failed');
    } catch (error) {
      console.error('Error downloading video:', error);
      throw error;
    }
  }

  // 获取视频 URI（主要方法）
  async getVideoUri(url: string): Promise<string> {
    // 进行URL编码，避免空格等特殊字符影响缓存路径
    const encodedUrl = encodeURI(url);
    try {
      const filePath = this.getCacheFilePath(encodedUrl);
      const isCached = await this.isVideoCached(encodedUrl);

      if (isCached) {
        return `file://${filePath}`;
      }

      // 如果是包内资源，则跳过，返回原始URL
      // if (filePath.startsWith('/') || url.startsWith('bundle://')) {
      //   return url;
      // }

      await this.downloadVideo(encodedUrl, filePath);
      return `file://${filePath}`;
    } catch (error) {
      console.error('Failed to get video URI:', error);
      // 如果缓存失败，返回原始URL
      return encodedUrl;
    }
  }

  deleteFolder = async (folderPath: string) => {
    try {
      // 读取文件夹中的所有文件
      const files = await RNFS.ls(folderPath);

      for (const file of files) {
        const filePath = folderPath + '/' + file;

        // 如果是文件，删除文件
        if (await RNFS.isDir(filePath)) {
          await this.deleteFolder(filePath);
        } else {
          await RNFS.unlink(filePath);
        }
      }
      // 删除空文件夹
      await RNFS.unlink(folderPath);
      console.log('文件夹删除成功:', folderPath);
    } catch (error) {
      console.error('删除文件夹失败:', error);
    }
  };

  // 清理缓存
  async clearCache(): Promise<void> {
    try {
      await this.deleteFolder(this.cacheDir);
      console.log('文件夹删除成功:', this.cacheDir);
    } catch (error) {
      console.error('删除文件夹失败:', error);
    }
  }
}

// 导出单例
export const videoCache = new VideoCacheManager();
